package com.work.module_base.utils;


import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * @desc: RSA 密钥工具
 * @auth: zhangsy
 * @data: 2019/9/5 9:07
 */
public class RSAUtils {

    public static final String KEY_ALGORITHM = "RSA";
//    public static final String KEY_ALGORITHM = "RSA/ECB/PKCS1Padding";

    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    public static final String PUBLIC_KEY = "RSAPublicKey";

    public static final String PRIVATE_KEY = "RSAPrivateKey";

    private static final int MAX_ENCRYPT_BLOCK = 117;

    private static final int MAX_DECRYPT_BLOCK = 128;

    private RSAUtils() {
    }

    /**
     * @auth: zhangsy
     * @desc: 生成密码对
     * @data: 2019/9/5 9:08
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }


    /**
     * @auth: zhangsy
     * @desc: 解密数据
     * @data: 2019/9/5 9:09
     * @return:
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * @desc: 公钥解密
     * @auth: zhangsy
     * @data: 2019/9/17 11:56
     * @return:
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * @desc: 公钥加密
     * @auth: zhangsy
     * @data: 2019/9/17 11:56
     * @return:
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        String alarm = keyFactory.getAlgorithm();
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }


    public static String encryptByPublicKey(String data, String publickey) {
        try {
            data = Base64Utils.encode(encryptByPublicKey(data.getBytes(), publickey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static void main(String[] args) throws Exception {
//        Map<String, Object> stringObjectMap = genKeyPair();
//        String privateKey = getPrivateKey(stringObjectMap);
//        String publicKey = getPublicKey(stringObjectMap);
        String aseKey = "";
        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJeGUOnyThSfVbKV0EAF5kkDHA9LN3CHQqXTpnuz6mjYH89v7F44iAiDgAqz3JGVe/4r9EV69zmnXqMfJMYop8+78XMF+3j3z+3Ah5w7eJOee2KxyxU3RSeUfZ7yL5sywbNvbIKkp5tSbYzrJWymBa2DZbW6WhZCf/LC75Ao8QAZAgMBAAECgYA+5jXOd5QsAVxsrr3s5cYLhuvt+VZBMxTai3pvnWbwMM87qAVhs2vcxOGxD6q/EGORRiO3d+0KlMy3QCVe0N+fu4+4bkvAx5mrgGNBiDLfUeaeFjAlQZUt9T2aPEaMEZLB4uDyjZp83n7lhufEHBQ1XTk2JXRvwo7uakrgbXCcBQJBAMxMM0L0LO2Odr6s6Tg2Oelhv5JyO3/NjUYmaHf+7n3V900xfU1PuqZ6NVQmFATXCwye/Diwr4rrNUsjS4clrT8CQQC93x7wgWajj03Ay6wVKaTqIFPt7suRCFLyHfeShsrC4KermYzNiG3QHZL84vS78PnVAylsVUYEbR/Fwd9lWASnAkAozVs7lwrWEyryIBSgLmxYiTY6qGfruYDqrscUmCzHoxE2MJkm9LKBh0zZVpWO9ef2CFa1d8xHgXxuWkk+X67/AkEAltCbar3eIRy6zeD5lvW1IKL9B4kd+N17xQU4mRKoC5MWm58j0D4Fu8FB98zuSDpot2IDjSFOtEVZb2NHZuA7EQJAb/K17bz/PAEH60buFOJ9yldzdhnLsnP7hzIalCzIdAtvQVPSTKkYpq9/DDRW0XCOWDu7lYSuQ2ScIecZxEznhQ==";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXhlDp8k4Un1WyldBABeZJAxwPSzdwh0Kl06Z7s+po2B/Pb+xeOIgIg4AKs9yRlXv+K/RFevc5p16jHyTGKKfPu/FzBft498/twIecO3iTnntiscsVN0UnlH2e8i+bMsGzb2yCpKebUm2M6yVspgWtg2W1uloWQn/ywu+QKPEAGQIDAQAB";
//        // 私钥加密
//        String s1 = encodeByPrivate(aseKey, privateKey);
//        System.out.println(s1);
//        // 公钥解密
//        String s2 = decryptByPublicKey(s1, publicKey);
//        System.out.println(s2);

        aseKey = "{\"password\":\"123\",\"telphone\":\"13223455432\"}";
        // 公钥加密
        String s3 = encryptByPublicKey(aseKey, publicKey);
        System.out.println(s3);

    }
}